<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增用户</el-button>
        <!-- <el-button v-auth="'batchAdd'" type="primary" :icon="Upload" plain @click="batchAdd">批量添加用户</el-button> -->
        <el-button v-auth="'export'" type="primary" :icon="Download" plain @click="webDerive">导出用户数据</el-button>
        <!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
        <!-- <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
          批量删除用户
        </el-button> -->
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- nameHeader -->
      <!-- <template #nameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template> -->
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <!--  -->
        <el-button type="text" @click="openEditMenu(scope.row.id)">权限设置</el-button>
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <UserDrawer ref="drawerRef" @change-status="changeStatus" />
    <ImportExcel ref="dialogRef" />
    <!-- 树形菜单 -->
    <el-dialog v-model="dialogVisible" title="权限设置" width="500" :before-close="handleClose">
      <!-- :default-expanded-keys="[1, 12]" -->
      <!-- :default-checked-keys="[2, 3]" -->
      <el-tree
        ref="ruleTree"
        style="max-width: 600px"
        :data="menuList"
        show-checkbox
        default-expand-all
        node-key="id"
        :props="defaultProps"
        @check-change="ruleChange"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveMenu"> 确 定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <el-dialog title="权限设置" v-model="dialogMenuVisible" @close="clearMenu">
      <el-tree
        ref="ruleTree"
        v-loading="ruleLoading"
        :data="menuList"
        show-checkbox
        default-expand-all
        node-key="id"
        :props="defaultProps"
        highlight-current
        @check-change="ruleChange"
      >
      </el-tree>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="clearMenuDialog">取 消</el-button>
          <el-button type="primary" @click="saveMenu">确 定</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup lang="tsx" name="用户管理">
import { ref, reactive } from "vue";
// import { useRouter } from "vue-router";
import { Tree } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
// import { useDownload } from "@/hooks/useDownload";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox, ElTree } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
// HeaderRenderScope
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
// Refresh，Upload
import { CirclePlus, Delete, EditPen, Download, View } from "@element-plus/icons-vue";
import { getUserList, deleteUser, editUser, addUser, updateUserStatus } from "@/api/modules/userManage";
import { userStatus } from "@/utils/dict";
// import * as XLSX from "XLSX";
import { exportExcel } from "@/utils/ExportExcel";
import { getMenuTreeAll, getMenuIds, updateUserMenu, getUserTreeMenu } from "@/api/modules/menu";
import type Node from "element-plus/es/components/tree/src/model/node";
// import {  getMenuTreeAll } from "@/api/modules/menu";

// 权限
const defaultProps = {
  children: "children",
  label: "name"
};
// const data = ref([
//   {
//     id: 1,
//     name: "Level one 1",
//     children: [
//       {
//         id: 4,
//         name: "Level two 1-1",
//         children: [
//           {
//             id: 9,
//             name: "Level three 1-1-1"
//           },
//           {
//             id: 10,
//             name: "Level three 1-1-2"
//           }
//         ]
//       }
//     ]
//   },
//   {
//     id: 2,
//     name: "Level one 2",
//     children: [
//       {
//         id: 5,
//         name: "Level two 2-1"
//       },
//       {
//         id: 6,
//         name: "Level two 2-2"
//       }
//     ]
//   },
//   {
//     id: 3,
//     name: "Level one 3",
//     children: [
//       {
//         id: 7,
//         name: "Level two 3-1"
//       },
//       {
//         id: 8,
//         name: "Level two 3-2"
//       }
//     ]
//   }
// ]);
const dialogVisible = ref(false);
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确定取消修改吗?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
// const dialogMenuVisible = ref(false);
// const ruleLoading = ref(false);
const menuList = ref(); // 总菜单
const userIdMenuList = ref(); //
const parentIdArr: any = ref([]); //
const ruleTree = ref<InstanceType<typeof ElTree>>(); //
const userForm = ref({ id: -1, status: -1 }); //
const dataForm = reactive({
  userId: "",
  permissionList: []
});
// const defaultProps = ref({
//   children: "children",
//   label: "name"
// });
// const clearMenu = () => {
//   console.log("clearMenu");
// };
const ruleChange = (node: Node, check: Tree.menuObject) => {
  console.log(node, "node");
  console.log(check, "check");
  let myMenuList: any = dataForm.permissionList;
  if (check) {
    myMenuList.push(node.id);
    myMenuList = [...new Set(myMenuList)];
  } else {
    // 获取选中的菜单的已选中的子级
    myMenuList.forEach((item, index) => {
      if (item === node.id) {
        myMenuList.splice(index, 1);
      }
    });
  }
  console.log(myMenuList, "ids");
};
// // 取消权限菜单 对话框
// const clearMenuDialog = () => {
//   dialogMenuVisible.value = false;
//   // 清空
//   if (ruleTree.value) {
//     ruleTree.value.setCheckedKeys([]);
//   }
//   console.log("clearMenuDialog");
// };
// // 请求菜单
const getMenuTreeAllFn = () => {
  // ruleLoading.value = true;
  getMenuTreeAll().then(res => {
    // console.log(res, "res");
    //
    menuList.value = res.data;
    // ruleLoading.value = false;
    // this.total = res.data.total;
  });
};
// // 根据id请求菜单

const getUserMenu = (id: number) => {
  // ruleLoading.value = true;
  getMenuIds(id).then(response => {
    userIdMenuList.value = response.data;
    console.log(userIdMenuList.value, "userIdMenuList");
    // ruleLoading = false
    // total = response.data.total;
    if (response.data.length !== 0) {
      getUserTreeMenu().then(res => {
        // ruleLoading.value = false;
        // console.log(res, "res");
        res.data.forEach(item => {
          // console.log(item, "item");
          // console.log(parentIdArr.value, "parentIdArr.value");
          collectIdsWithChildren(item, parentIdArr.value);
        });
        // console.log(userIdMenuList, "userIdMenuList");
        // console.log(parentIdArr.value, "parentIdArr");
        const newMenuList = userIdMenuList.value.filter(item => !parentIdArr.value.includes(item));
        console.log(newMenuList, "newMenuList");
        // $refs.ruleTree.setCheckedKeys(userIdMenuList);
        ruleTree.value!.setCheckedKeys(newMenuList);
      });
    }
  });
};
// 确定权限
const saveMenu = () => {
  //
  console.log(dataForm.permissionList, "this.dataForm.permissionList");
  dialogVisible.value = false;
  const params = {
    menu_ids: dataForm.permissionList,
    user_id: userForm.value.id
  };
  updateUserMenu(params.user_id, params.menu_ids)
    .then(response => {
      console.log(response.data);
      ElMessage.success("修改成功");
      // this.userList = response.data.data;
      // this.total = response.data.total;
    })
    .catch(err => {
      ElMessage.success(err);
    });
};
// // 编辑菜单
const openEditMenu = (id: number) => {
  dialogVisible.value = true;
  getMenuTreeAllFn();
  console.log(id, "id");
  userForm.value.id = id;
  // dialogMenuVisible.value = true;
  // // 初始化
  if (ruleTree.value) {
    ruleTree.value.setCheckedKeys([], false);
  }
  getUserMenu(id);
};
const collectIdsWithChildren = (item, parentIdArr) => {
  if (item.children && item.children.length > 0) {
    // this.$set(parentIdArr, parentIdArr.length, item.id);
    parentIdArr.push(item.id);
    item.children.forEach(child => {
      collectIdsWithChildren(child, parentIdArr);
    });
  }
};

// 修改启用状态
const changeStatus = row => {
  if (!row.id) return;
  console.log(row.status, "status");
  const status = row.status ? "启用" : "禁用";
  ElMessageBox.confirm(`您确认${status}用户?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      console.log(row, "userForm");
      updateUserStatus({ user_id: row.id, status: row.status }).then(() => {
        ElMessage({
          type: "success",
          // message: response.msg,
          message: status + "成功"
        });
        // getUserList();
        proTable.value?.reset();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已禁用用户"
      });
    });
};

// const router = useRouter();

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && page && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data, "data");
  return {
    list: data.data,
    total: data.total,
    page: data.page,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // delete newParams.createTime;
  params.page || (newParams.page = 1);
  params.pageSize || (newParams.pageSize = 10);
  console.log(params, "params");
  console.log(getUserList(newParams), "get");
  return getUserList(newParams);
};

// 表格配置项
const columns = reactive<ColumnProps<Tree.ResAreaList>[]>([
  // { type: "selection", fixed: "left", width: 70 },
  // { type: "sort", label: "排序", width: 80 },
  {
    type: "index",
    label: "索引",
    width: 85
  }, //
  { type: "expand", label: "展开", width: 85 }, //
  {
    prop: "account",
    label: "账号",
    search: { el: "input" },
    width: 136
  },
  {
    prop: "name",
    label: "用户名",
    search: { el: "input" },
    width: 136
  },
  { prop: "mobile", label: "手机号", search: { el: "input" }, width: 120 },
  { prop: "memo", label: "备注", search: { el: "input" }, width: 120 },
  {
    prop: "status",
    label: "状态",
    tag: true,
    sortable: true, // 排序
    enum: userStatus,
    search: { el: "tree-select" },
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "created_at",
    label: "创建时间",
    // headerRender,
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  {
    prop: "updated_at",
    label: "更新时间",
    // headerRender,
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除用户信息
const deleteAccount = async (params: Tree.ResAreaList) => {
  await useHandleData(deleteUser, { user_id: params.id }, `删除【${params.name}】用户`);
  proTable.value?.getTableList();
};

// 格到本地xlsx文件 ----
const webDerive = () => {
  ElMessageBox.confirm("是否确认导出当前页面数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    //deleteDate  选中数据列表
    let titleArr = ["序号", "账号", "用户名称", "备注", "手机号", "创建时间", "更新时间", "状态"];
    const oldTableData = JSON.parse(JSON.stringify(proTable.value?.tableData));
    const filterVal = ["index", "account", "name", "memo", "mobile", "created_at", "updated_at", "status"];
    const newTableData = oldTableData.map((v, i) =>
      filterVal.map(j => {
        if (j === "index") {
          return i;
        } else if (j === "status") {
          return v[j] === 0 ? "禁用" : "正常";
        } else {
          return v[j];
        }
      })
    );
    const item = oldTableData[0];
    console.log(newTableData, "newTableData");
    const title = `${item.name} - ${new Date().toLocaleString().replaceAll("/", "-")}`;
    exportExcel({
      json: newTableData, //数据
      name: title, //表名
      titleArr: titleArr, //表头
      sheetName: "sheet" //页签
    });
  });
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
// const batchAdd = () => {
//   const params = {
//     title: "用户",
//     tempApi: exportUserInfo,
//     importApi: BatchAddUser,
//     getTableList: proTable.value?.getTableList
//   };
//   dialogRef.value?.acceptParams(params);
// };

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Tree.ResAreaList> = {}) => {
  row = title === "新增" ? {} : row;
  const params = {
    title,
    isView: title === "查看",
    row: title === "新增" ? {} : { ...row },
    api: title === "新增" ? addUser : title === "编辑" ? editUser : undefined,
    getTableList: proTable.value?.getTableList
  };
  console.log(title, "title----");
  console.log(params, "params----");
  drawerRef.value?.acceptParams(params);
};
</script>
@/utils/ExportExcel
